var x=0 
var time=0
var lighting=0
const devicesId = "859459085" 
const api_key = "QB6OAO=1m10T7Ay90MuBVzlxsx4=" 
const music = wx.createInnerAudioContext()
music.src = 'https://636c-cloud1-9gyu42ww9a54ce2d-1307742600.tcb.qcloud.la/%E4%B8%89%E6%A3%AE%E6%A1%90%E4%B9%83%20-%20bgm002.mp3?sign=4a37029963b61a5e01f415f5f2a6842f&t=1645089897'
let data1={"datastreams": [{"id": "X","datapoints":[{"value": 1}]},]}
let data0={"datastreams": [{"id": "X","datapoints":[{"value": 0}]},]}
Page({
    data:{
      a:"",
    },
    inputtime(e){
        x=e.detail.value
    },
    gettime(){
        time=x
        x=0
        this.setData({
            a:""
        })
        //console.log(time)
        if(time!=0){
        wx.showToast({
          title: '计时开始',
          icon: 'success',
          duration: 2000
        })
        setTimeout(()=>{this.warning()},time*60000)
      }
    },
    warning(){
      this.getDatapoints().then(()=>{
        console.log(lighting)
        if(lighting<=350){
          music.play()
          let that=this
          that.sendDatapoints1()
          wx.showModal({
            title: '提示',
            content: '已达到设定时长，请及时关灯！',
            confirmText: '关闭提示',
            cancelText: '延长10分',
            success: function(res) {
              music.stop()
              that.sendDatapoints0()
              if (res.confirm) {
                console.log('用户点击主操作')
              } else if (res.cancel) {
                console.log('用户点击次要操作')
                setTimeout(()=>{that.warning()},600000)
              }
            }
          })
        }
          if(lighting>350){
            wx.showToast({
              title: '计时结束',
              icon: 'success',
              duration: 5000
            })
          }
    })
    },
    onPullDownRefresh: function () {
      wx.showLoading({
        title: "正在获取"
      })
      this.getDatapoints().then(() => {
        wx.hideLoading()
      }).catch((error) => {
        wx.hideLoading()
        console.error(error)
      })
      wx.stopPullDownRefresh()
    },
    onLoad: function () {
      console.log(`your deviceId: ${devicesId}, apiKey: ${api_key}`)
      wx.showLoading({
        title: '加载中'
      })
      this.getDatapoints().then(() => {
        wx.hideLoading()
      }).catch((err) => {
        wx.hideLoading()
        console.error(err)
      })
    },
    getDatapoints: function () {
      return new Promise((resolve, reject) => {
        wx.request({
          url: `https://api.heclouds.com/devices/${devicesId}/datapoints?datastream_id=Lighting&
   limit=20`,
          header: {
            'content-type': 'application/json',
            'api-key': api_key
          },
          success: (res) => {
            const status = res.statusCode
            const response = res.data
            if (status !== 200) {
              reject(res.data)
              return ;
            }
            if (response.errno !== 0) { 
              reject(response.error)
              return ;
            }
            if (response.data.datastreams.length === 0) {
              reject("当前设备无数据, 请先运行硬件实验")
            }
            resolve({
              lighting:response.data.datastreams[0].datapoints.reverse()[0]
            })
              lighting= response.data.datastreams[0].datapoints.reverse()[0].value
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    },
    sendDatapoints1: function () {
      wx.request({
        url: `https://api.heclouds.com/devices/${devicesId}/datapoints`,
        header: {
          'content-type': 'application/json',
          'api-key': api_key
        },
        method: 'POST',
        data:JSON.stringify(data1),
        success(res){
          console.log("更新数据成功",res)
        },
        fail: function(res){
          wx.showToast({ title: '系统错误' })
        },
        complete:function(res){
          wx.hideLoading()
        }
      })
    },
    sendDatapoints0: function () {
      wx.request({
        url: `https://api.heclouds.com/devices/${devicesId}/datapoints`,
        header: {
          'content-type': 'application/json',
          'api-key': api_key
        },
        method: 'POST',
        data:JSON.stringify(data0),
        success(res){
          console.log("更新数据成功",res)
        },
        fail: function(res){
          wx.showToast({ title: '系统错误' })
        },
        complete:function(res){
          wx.hideLoading()
        }
      })
    }
})